//
//  HomeTableViewController.swift
//  WeiBo
//
//  Created by wukeng on 16/8/21.
//  Copyright © 2016年 wukeng. All rights reserved.
//

import UIKit
import SDWebImage

class HomeTableViewController: BaseTableViewController {
    
    lazy var titleBtn : TitleButton = TitleButton()
    lazy var statuses : [StatusViewModel] = [StatusViewModel]()
    
    private lazy var popView : PopoverAnimator = PopoverAnimator { (Presented) in
        self.titleBtn.selected = Presented
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        v.addRotationAnimator()
        setupNavigationBar()
        loadStatuses()
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 20
    }
}

// MARK: - 设置UI
extension HomeTableViewController{
    private func setupNavigationBar(){
        if !isLogin{
            return
        }
        //设置左侧的Item
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
        //设置右侧的Item
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        //设置titleView
        titleBtn.setTitle("吴铿的微博", forState: .Normal)
        navigationItem.titleView = titleBtn
        titleBtn.addTarget(self, action: #selector(HomeTableViewController.titleBtnClick(_:)), forControlEvents: .TouchUpInside)
    }
}

// MARK: - 事件监听函数
extension HomeTableViewController {
    func titleBtnClick(titleBtn : TitleButton) {
        //创建控制器
        let vc = PopoverViewController()
        vc.modalPresentationStyle = .Custom
        //设置转场代理
        vc.transitioningDelegate = popView
        popView.presentedFrame = CGRect(x: UIWidth / 2 - 90, y: 55, width: 180, height: 250)
        //弹出控制器
        presentViewController(vc, animated: true, completion: nil)
    }
}

// MARK: - 请求数据
extension HomeTableViewController{
    private func loadStatuses(){
        NetworkTools.shareInstance.loadStatuses { (result, error) in
            if error != nil{
                print(error)
                return
            }
            guard let resultArray = result else{
                return
            }
            for statusDict in resultArray{
                let status = Status(dict: statusDict)
                let sVM = StatusViewModel(status: status)
                self.statuses.append(sVM)
            }
            self.cacheImages(self.statuses)
        }
    }
    
    private func cacheImages(viewModel : [StatusViewModel]){
        //创建组
        let group  = dispatch_group_create()
        for viewModel in viewModel {
            for picURL in viewModel.picURLs {
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(picURL, options: [], progress: nil, completed: { (_, _, _, _, _) in
                    print("下载了一张图片")
                    dispatch_group_leave(group)
                })
            }
        }
        //刷新表格
        dispatch_group_notify(group, dispatch_get_main_queue()) { 
            self.tableView.reloadData()
            print("刷新表格")
        }
    }
}

// MARK: - 表格数据源代理
extension HomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView .dequeueReusableCellWithIdentifier("HomeCellID")! as! HomeViewTableViewCell
        cell.viewModel = statuses[indexPath.row]
        return cell
    }
}













